package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class LessonPayStatusListener {

    private final ILearningLessonService lessonService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "learning.lesson.pay.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO orderBasicDTO){
        // 1. 参数校验
        if(orderBasicDTO == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds()) || orderBasicDTO.getUserId() == null){
            log.error("监听订单支付消息异常");
            return;
        }
        // 2. 保存课程到课表
        lessonService.addUserLesson(orderBasicDTO.getUserId(), orderBasicDTO.getCourseIds());
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "learning.lesson.refund.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenLessonRefund(OrderBasicDTO orderBasicDTO){
        // 1. 参数校验
        if(orderBasicDTO == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds()) || orderBasicDTO.getUserId() == null){
            log.error("监听订单支付消息异常");
            return;
        }
        // 2. 保存课程到课表
        lessonService.deleteLession(orderBasicDTO.getUserId(), orderBasicDTO.getCourseIds());
    }

}
